<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      v-loading="formLoading"
    >
      <el-row :gutter="20">
        <!-- 左列 -->
        <el-col :span="14">
          <!-- 动态证件输入 -->
          <el-form-item :label="idLabel" :prop="idField">
            <el-input
              :model-value="getDynamicField(idField)"
              @update:model-value="(val) => setDynamicField(idField, val)"
              :placeholder="`请输入${idLabel}`"
            />
          </el-form-item>

          <el-form-item label="人员姓名" prop="name">
            <el-input v-model="formData.name" placeholder="请输入姓名"/>
          </el-form-item>

          <el-form-item label="人员性别" prop="sex">
            <el-radio-group v-model="formData.sex">
              <el-radio
                v-for="dict in getIntDictOptions(DICT_TYPE.SYSTEM_USER_SEX)"
                :key="dict.value"
                :value="dict.value"
              >
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="管控单位" prop="deptId">
            <el-tree-select
              v-model="formData.deptId"
              :data="deptList"
              :props="defaultProps"
              check-strictly
              node-key="id"
              :default-expanded-keys="defaultExpandedKeys"
              placeholder="请选择管控单位"
            />
          </el-form-item>
        </el-col>

        <!-- 右列 -->
        <el-col :span="10">
          <el-form-item label="头像" prop="avatar" class="no-label-width">
            <UploadImg v-model="formData.avatar" :limit="1" :is-show-tip="false"/>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 下方其他表单项 -->
      <el-form-item label="人员标签" prop="tagIds">
        <MemberTagSelect v-model="formData.tagIds" show-add/>
      </el-form-item>

      <el-form-item label="人员分类" prop="groupId">
        <MemberGroupSelect v-model="formData.groupId"/>
      </el-form-item>

      <el-form-item label="电话号码" prop="phoneNumber">
        <el-input v-model="formData.phoneNumber" placeholder="请输入电话号码，多个逗号隔开"/>
      </el-form-item>

      <el-form-item label="车牌号码" prop="carNumber">
        <el-input v-model="formData.carNumber" placeholder="请输入车牌号码，多个逗号隔开"/>
      </el-form-item>

      <el-form-item label="人员备注" prop="remark">
        <el-input
          v-model="formData.remark"
          placeholder="请输入备注"
          type="textarea"
          :rows="2"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import * as UserApi from '@/api/member/user'
import * as AreaApi from '@/api/system/area'
import MemberTagSelect from '@/views/member/tag/components/MemberTagSelect.vue'
import MemberGroupSelect from '@/views/member/group/components/MemberGroupSelect.vue'
import { defaultProps, handleTree } from "@/utils/tree"
import * as DeptApi from '@/api/system/dept'
import { DeptVO } from "@/api/system/dept"
// import type { Tree } from "@/utils/tree"

interface Props {
  userType: 'idcard' | 'passport' // 控制表单模式
  foreigner: number // 明确要求传入 foreigner 值
}

const props = withDefaults(defineProps<Props>(), {
  foreigner: 2 // 默认国内用户
})

// 定义计算属性（修复错误1和2）
const idField = computed(() => props.userType === 'idcard' ? 'idcard' : 'passportNumber')
const idLabel = computed(() => props.userType === 'idcard' ? '身份证' : '护照号')

const { t } = useI18n()
const message = useMessage()
const emit = defineEmits(['success'])

// 动态字段配置
const idConfig = computed(() => ({
  field: props.userType === 'idcard' ? 'idcard' : 'passportNumber',
  label: props.userType === 'idcard' ? '身份证' : '护照号',
  ruleMessage: props.userType === 'idcard' ? '身份证号码不能为空' : '护照号码不能为空'
}))

// 表单验证规则
const formRules = reactive({
  [idConfig.value.field]: [{
    required: true,
    message: idConfig.value.ruleMessage,
    trigger: 'blur'
  }]
})

// 组件状态
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref('')
const formRef = ref()

// 部门数据
const depts = ref<DeptVO[]>([])
const deptList = ref<Tree[]>([])
const defaultExpandedKeys = ref<number[]>([])

// 地区数据
const areaList = ref([])

interface FormData {
  // 基础信息
  id?: number
  name?: string
  sex?: number
  avatar?: string
  remark?: string
  foreigner: number // 必须字段，不可为undefined

  // 证件信息
  idcard?: string
  passportNumber?: string
  mobile?: string

  // 组织信息
  deptId?: number
  deptName?: string
  groupId?: number
  tagIds?: number[]

  // 联系信息
  phoneNumber?: string
  carNumber?: string

  // 地址信息
  areaId?: number
  liveAddress?: string
  birthPlace?: string

  // 其他个人信息
  country?: string
  nation?: string
  faith?: string
  enFirstName?: string
  enSecondName?: string
  birthday?: string

  // 系统信息
  status?: number
  password?: string
  nickname?: string
  mark?: string

  // 动态字段访问签名
  [key: string]: string | number | number[] | undefined
}

// 表单数据（包含所有可能字段）
const initFormData = (): FormData => ({
  foreigner: props.foreigner,
  id: undefined,
  name: undefined,
  sex: undefined,
  avatar: undefined,
  remark: undefined,
  idcard: props.userType === 'idcard' ? '' : undefined,
  passportNumber: props.userType === 'passport' ? '' : undefined,
  mobile: undefined,
  deptId: undefined,
  deptName: undefined,
  groupId: undefined,
  tagIds: [],
  phoneNumber: undefined,
  carNumber: undefined,
  areaId: undefined,
  liveAddress: undefined,
  birthPlace: undefined,
  country: undefined,
  nation: undefined,
  faith: undefined,
  enFirstName: undefined,
  enSecondName: undefined,
  birthday: undefined,
  status: undefined,
  password: undefined,
  nickname: undefined,
  mark: undefined
})

const formData = ref<FormData>(initFormData())

// 加载部门数据
const loadDeptData = async () => {
  try {
    depts.value = await DeptApi.getSimpleDeptList()
    deptList.value = handleTree(depts.value)
    defaultExpandedKeys.value = depts.value
      .filter(dept => (!dept.parentId || dept.parentId === 0) && dept.id !== undefined)
      .map(dept => dept.id!)
  } catch (error) {
    console.error('加载部门数据失败:', error)
    message.error('加载部门数据失败')
  }
}

// 查找部门
const findDeptById = (id: number): DeptVO | undefined => {
  return depts.value.find(dept => dept.id === id)
}

// 重置表单
const resetForm = () => {
  formData.value = {
    id: undefined,
    [idConfig.value.field]: undefined,
    name: undefined,
    sex: undefined,
    deptId: undefined,
    deptName: undefined,
    avatar: undefined,
    tagIds: [],
    groupId: undefined,
    phoneNumber: undefined,
    carNumber: undefined,
    remark: undefined,
    foreigner: props.foreigner, // 保持传入的 foreigner 值

    // 重置其他字段
    mobile: undefined,
    password: undefined,
    status: undefined,
    nickname: undefined,
    areaId: undefined,
    birthday: undefined,
    mark: undefined,
    country: undefined,
    nation: undefined,
    faith: undefined,
    enFirstName: undefined,
    enSecondName: undefined,
    liveAddress: undefined,
    birthPlace: undefined
  }
  formRef.value?.resetFields()
}

// 打开弹窗
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  try {
    formLoading.value = true

    // 并行加载数据
    await Promise.all([
      // 如果是编辑模式，加载用户数据
      id ? UserApi.getUser(id).then(res => {
        formData.value = { ...formData.value, ...res }
      }) : Promise.resolve(),

      // 加载地区数据
      AreaApi.getAreaTree().then(res => {
        areaList.value = res
      }),

      // 加载部门数据
      loadDeptData()
    ])
  } catch (error) {
    console.error('加载数据失败:', error)
    message.error('加载数据失败')
  } finally {
    formLoading.value = false
  }
}

// 提交表单
const submitForm = async () => {
  try {
    // 验证表单
    if (!formRef.value) return
    const valid = await formRef.value.validate()
    if (!valid) return

    formLoading.value = true

    // 设置部门名称
    if (formData.value.deptId) {
      const dept = findDeptById(formData.value.deptId)
      formData.value.deptName = dept?.name || ''
    }

    // 确保 foreigner 使用传入的值
    formData.value.foreigner = props.foreigner

    // 提交数据
    const data = formData.value as unknown as UserApi.UserVO
    if (formType.value === 'create') {
      await UserApi.createUser(data)
      message.success(t('common.createSuccess'))
    } else {
      await UserApi.updateUser(data)
      message.success(t('common.updateSuccess'))
    }

    dialogVisible.value = false
    emit('success')
  } catch (error) {
    console.error('提交表单失败:', error)
    message.error('提交表单失败')
  } finally {
    formLoading.value = false
  }
}

// 确保v-model绑定正确
// 安全获取动态字段值
const getDynamicField = (field: 'idcard' | 'passportNumber'): string | undefined => {
  return formData.value[field]
}

// 安全设置动态字段值
const setDynamicField = (field: 'idcard' | 'passportNumber', value: string) => {
  formData.value[field] = value
}

// 暴露方法
defineExpose({ open })
</script>
